package com.ruoyi.common.core.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.web.domain.BaseEntity;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author : gsi
 * @date : 2024-09-05
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {

        if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
            baseEntity.setCreateBy(String.valueOf(SecurityContextHolder.getUserId()));
            baseEntity.setCreateTime(new Date());
            baseEntity.setCreateByName(SecurityContextHolder.getUserName());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
            baseEntity.setUpdateBy(String.valueOf(SecurityContextHolder.getUserId()));
            baseEntity.setUpdateTime(new Date());
            baseEntity.setCreateByName(SecurityContextHolder.getUserName());
        }
    }
}
